package com.bjpowernode.powernotify.listener;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.bjpowernode.powernotify.common.enums.KeyConstants;
import com.bjpowernode.powernotify.common.util.MQUtil;
import com.bjpowernode.powernotify.domain.MessageWrapper;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class MessageQueueListener {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    //读取
    public void read(){
        ListOperations<String,String> listOps = stringRedisTemplate.opsForList();
        try {
            while (true) {
                String mqJsonText = listOps.rightPopAndLeftPush(KeyConstants.GATEWAY_NOTIFY_ORIGIN.getKey(),KeyConstants.GATEWAY_NOTIFY_BACK.getKey(),300, TimeUnit.MILLISECONDS);
                System.out.println("--->"+ DateUtil.now()+"|消费者读取Redis的消息数据--->"+mqJsonText);
                if(StrUtil.isBlank(mqJsonText)){
                    TimeUnit.SECONDS.sleep(2);
                }else{
                    System.out.println("--->"+DateUtil.now()+"|消费者添加消息到DelayedQueue中");
                    //读取到mq的数据
                    MessageWrapper messageWrapper = MQUtil.createMessageWrapper(mqJsonText);
                    //将MessageWrapper作为PollingTask参数,将PollingTask加入到DelayedQueue
                    MQUtil.addPollingTaskToQueue(messageWrapper);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
